from selenium import webdriver
from .base import file_save,file_load
import requests
from requests.cookies import RequestsCookieJar
import urllib.parse

class GetCookie:
    def __init__(self,cookiename, url='''https://www.haibeisuifang.com/''' ):
        '''手动获取cookie'''
        self.driver = webdriver.Edge()
        self.url = url
        self.cookiename = cookiename
        self.get_cookies()

    def get_cookies(self):
        try:
            self.driver.get(self.url)
            input("准备好网页后，回车")
            cookies = self.driver.get_cookies()
            file_save(self.cookiename,cookies)
            print(f'获取cookie成功')
        except Exception as e:
            print(e)
            print("获取Cookies失败")
        finally:
            self.driver.close()
            
def get_session(cookiename,headers= {'User-Agent':'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/120.0.0.0 Safari/537.36'}):
    se = requests.session()
    tmp_cookies = RequestsCookieJar()
    if headers:
        se.headers.update(headers)    
    datas = file_load(cookiename)
    for item in datas:
        tmp_cookies.set(item["name"], item["value"])
        se.cookies.update(tmp_cookies)
    return se
    

def url_to_dic(string): 
    '''将原始表单数据转化为字典数据'''
    # 原始参数字符串
    params = string
    # 手动解析
    params_dict = {}
    for param in params.split("&"):
        key, value = param.split("=")
        params_dict[key] = urllib.parse.unquote(value)
    # print(params_dict)
    return params_dict

def url_to_list(string): 
    '''将原始表单数据转化为字典数据'''
    # 原始参数字符串
    params = string
    # 手动解析
    params_list = []
    for param in params.split("&"):
        key, value = param.split("=")
        params_list.append((key, urllib.parse.unquote(value)))
    # print(params_dict)
    return params_list